package tiandang.core.service.impl;

import com.alibaba.druid.util.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tiandang.core.dao.*;
import tiandang.core.model.*;
import tiandang.core.service.ExportService;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExportServiceImpl implements ExportService {

  @Autowired
  private OrderMapper orderMapper;

  @Autowired
  private PromoMapper promoMapper;

  @Autowired
  private ManagerMapper managerMapper;

  @Autowired
  private OrderProductMapper orderProductMapper;

  @Autowired
  private ProductMapper productMapper;

  @Override
  public void exportOrder(Long startTimestamp, Long endTimestamp, String managerName,
                          String productName, Integer deliveryStatus, String orderId, HttpServletResponse response) throws Exception {
    List<OrderInfo> orderList = new ArrayList<>();

    //开团开始时间和结束时间不为空
    if (startTimestamp != null && endTimestamp != null) {
      orderList = orderMapper.getAllByPromoTime(startTimestamp, endTimestamp);
    }

    //团长名字不为空
    if (!StringUtils.isEmpty(managerName)) {
      orderList = orderMapper.getAllByManagerName(managerName);
    }

    //商品名称不为空
    if (!StringUtils.isEmpty(productName)) {
      orderList = orderMapper.getAllByProductName(productName);
    }

    if (deliveryStatus != null) {
      orderList = orderMapper.getAllByDeliveryStatus(deliveryStatus);
    }

    if (!StringUtils.isEmpty(orderId)) {
      OrderInfo order = orderMapper.selectByPrimaryKey(orderId);
      if (order != null) {
        orderList.add(order);
      }

    }

    if (startTimestamp == null && endTimestamp == null && StringUtils.isEmpty(managerName)
      && StringUtils.isEmpty(productName) && deliveryStatus == null && StringUtils.isEmpty(orderId)) {
      //获取全部订单数据
      orderList = orderMapper.getAll();
    }

    if (orderList.size() > 0) {
      orderList = addOrderRelative(orderList);
    }

    //拼装excel数据
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    List<ExportModel> exportModelList = new ArrayList<>();
    for (OrderInfo order : orderList) {
      for (OrderProduct orderProduct : order.getOrderProductList()) {
        ExportModel exportModel = new ExportModel();
        exportModel.setMangerName(order.getManager().getName());
        exportModel.setTime(dateFormat.format(order.getPromo().getStartTimestamp()));
        exportModel.setOrderId(order.getId());
        exportModel.setAddress(order.getPickAddress());
        exportModel.setCustomerName(order.getName());
        exportModel.setPhone(order.getPhone());
        exportModel.setProductName(orderProduct.getName());
        exportModel.setNumber(orderProduct.getProductNumber());
        exportModel.setPrice(orderProduct.getPresentPrice());
        exportModel.setMoney(orderProduct.getPresentPrice().multiply(new BigDecimal(orderProduct.getProductNumber())));
        exportModel.setRemarks(order.getRemarks());
        if (order.getPayStatus() == 0) {
          exportModel.setPayText("未支付");
        } else {
          exportModel.setPayText("已支付");
        }

        if (order.getDeliveryStatus() == 0) {
          exportModel.setDeliveryText("未发货");
        } else {
          exportModel.setDeliveryText("已发货");
        }

        exportModelList.add(exportModel);
      }
    }

    exportExcel(exportModelList, response);
  }

  private void exportExcel(List<ExportModel> exportModelList, HttpServletResponse response) throws Exception {
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("甜档小程序订单");
    HSSFRow row = sheet.createRow((int) 0);

    String[] excelHeader = {"团长姓名", "开团时间", "订单号", "提货地点", "买家姓名", "买家电话",
      "商品名称", "数量", "单价", "金额", "买家备注", "是否支付", "是否发货"};
    for (int i = 0; i < excelHeader.length; i++) {
      HSSFCell cell = row.createCell(i);
      cell.setCellValue(excelHeader[i]);
      sheet.autoSizeColumn(i);
    }

    for (int i = 0; i < exportModelList.size(); i++) {
      row = sheet.createRow(i + 1);
      ExportModel exportModel = exportModelList.get(i);

      row.createCell(0).setCellValue(exportModel.getMangerName());
      row.createCell(1).setCellValue(exportModel.getTime());
      row.createCell(2).setCellValue(exportModel.getOrderId());
      row.createCell(3).setCellValue(exportModel.getAddress());
      row.createCell(4).setCellValue(exportModel.getCustomerName());
      row.createCell(5).setCellValue(exportModel.getPhone());
      row.createCell(6).setCellValue(exportModel.getProductName());
      row.createCell(7).setCellValue(exportModel.getNumber());
      row.createCell(8).setCellValue(exportModel.getPrice().toString());
      row.createCell(9).setCellValue(exportModel.getMoney().toString());
      row.createCell(10).setCellValue(exportModel.getRemarks());
      row.createCell(11).setCellValue(exportModel.getPayText());
      row.createCell(12).setCellValue(exportModel.getDeliveryText());
    }

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/x-download");
    String filename = "甜档小程序订单";
    filename = URLEncoder.encode(filename, "UTF-8");
    response.addHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
    OutputStream out = response.getOutputStream();
    wb.write(out);
    out.close();
  }


  private List<OrderInfo> addOrderRelative(List<OrderInfo> orderList) {
    //加上开团对象;团长对象
    List<Promo> promoList = promoMapper.getAll();
    List<Manager> managerList = managerMapper.getAll();
    List<OrderProduct> allOrderProducts = orderProductMapper.getAll();


    for (OrderInfo order : orderList) {
      for (Promo promo : promoList) {
        if (order.getPromoId().intValue() == promo.getId().intValue()) {
          order.setPromo(promo);
        }
      }
    }

    for (OrderInfo order : orderList) {
      for (Manager manager : managerList) {
        if (order.getManagerId().intValue() == manager.getId().intValue()) {
          order.setManager(manager);
        }
      }
    }

    for (OrderInfo order : orderList) {
      List<OrderProduct> orderProductList = new ArrayList<>();
      for (OrderProduct orderProduct : allOrderProducts) {
        if (order.getId().equals(orderProduct.getOrderId())) {
          orderProductList.add(orderProduct);
        }
      }
      order.setOrderProductList(orderProductList);
    }

    return orderList;
  }
}
